﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using PPI.Client.Interface;
using PPI.Client.Logic;
using PPI.Client.Logic.Delegate;
using PPI.Client.Logic.XML;
using PPI.Client.Utils;
using PPI.Entities;
using PPI.Entities.Lookup;
using PPI.Entities.Settings;

namespace PPI.Client.Presenter
{

    public class DeployDatabasePresenter : DeployDatabasePresenterBase
    {
        public DeployDatabasePresenter(IDeployDatabase view)
        :base(view)
        {
        }

        protected override void SetApplicationFiles()
        {
            m_WebFiles.Push(Constants.K_WEBAPPLICATIONMOBILE);
            m_LocalFiles.Push(Constants.K_LOCALAPPLICATIONMOBILE);
        }
        
        protected override void  CheckFilesAreUpdate()
        {
            bool filesToDelete = false;
            try
            {
                filesToDelete = LSettings.CheckLocalSettingsWithServer(new ESettingsDeploymentMobileGPS());
            }
            catch (Exception e)
            {
                filesToDelete = true;
            }
            if(filesToDelete)
            {
                if (File.Exists(Constants.K_LOCALAPPLICATIONMOBILE))
                    File.Delete(Constants.K_LOCALAPPLICATIONMOBILE);
            }
        }

        public string DeployGPS(EUtility utility, EVendor_Project project, EHandheld handheld, EVendor_Contact contact, EVendor vendor)
        {
            try
            {
                m_view.IsDownloading = true;
                m_SettingsBase = new ESettingsVersionMobileGPS();
                m_SettingsBase = LSettings.GetSetting(m_SettingsBase);

                string sourceDatabase =
                    LDeploy.StartDeployGPS(utility.Id, utility.Name, vendor.Id, vendor.Name, project.Id, project.Name,
                                           contact.Id, contact.Name, handheld.Id, handheld.Name, m_SettingsBase.SettingText);
                m_view.IsDownloading = false;
                return LDeploy.ParseDownloadDatabase(sourceDatabase);
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
                throw new Exception("Not enougth space in disk to copy the database, please delete old images in ftp");

            }
        }

    }
}
